/* eslint-disable no-console */
(function ($) {
    // 生效的类别名称
    const categoryName = '我的常用'

    // 禁用默认右键菜单
    $(document).on('contextmenu', '#content .row .url-card', (e) => {
        e.preventDefault();
    });

    // 右键点击显示菜单
    $('#content .row .url-card').on('contextmenu', function (e) {
        e.preventDefault();

        // 隐藏所有其他菜单
        $('.context-menu').removeClass('show');

        // 获取当前卡片数据
        const $card = $(this);
        const url = $card.find('a[data-url]').data('url');

        // 检查是否在常用中
        const isFavorite = checkIfFavorite(url);

        // 更新菜单项显示状态
        $card.find('.add-to-favorites').toggle(!isFavorite);
        $card.find('.remove-from-favorites').toggle(isFavorite);

        // 定位并显示菜单
        $card.find('.context-menu')
            .css({
                'top': `${e.clientY}px`,
                'left': `${e.clientX}px`
            })
            .addClass('show');
    });

    // 点击其他地方时隐藏菜单
    $(document).on('click', (e) => {
        if (!$(e.target).closest('.context-menu').length) {
            $('.context-menu').removeClass('show');
        }
    });

    // 添加到常用
    $(document).on('click', '#content .row .url-card .add-to-favorites', async function(e) {
        e.preventDefault();
        const $card = $(this).closest('.url-card');
        const url = $card.find('a[data-url]').data('url');
        const title = $card.find('a[data-url]').data('name');
        const description = $card.find('a[data-url]').data('description');
        const logo = $card.find('img').attr('src');

        // 获取卡片数据
        const cardData = {url, title, description, logo};

        // 添加到本地存储
        await addToFavorites(cardData);

        // 应用到生效区域
        await applyFavorites($card, cardData);

        // 隐藏菜单
        $('.context-menu').removeClass('show');

        // 添加关联图标
        addHeartIcon($card);
    });

    // 从常用中移除
    $(document).on('click', '#content .row .url-card .remove-from-favorites', async function(e) {
        e.preventDefault();

        const $card = $(this).closest('.url-card');
        const url = $card.find('a[data-url]').data('url');

        // 从本地存储移除
        await removeFromFavorites(url);

        // 从生效区域移除
        await removeFromFavoritesSection(url);

        // 隐藏菜单
        $('.context-menu').removeClass('show');

        // 清理关联图标
        const $removeIconCard = $('#content .row .url-card').find(`a[data-url="${url}"]`).closest('.url-card')
        removeHeartIcon($removeIconCard);
    });

    // 检查是否在常用中
    function checkIfFavorite(url) {
        const favorites = JSON.parse(localStorage.getItem('myFavorites') || '[]');
        return favorites.some(item => item.url === url);
    }

    // 添加到常用
    function addToFavorites(item) {
        const favorites = JSON.parse(localStorage.getItem('myFavorites') || '[]');
        if (!favorites.some(fav => fav.url === item.url)) {
            favorites.push(item);
            localStorage.setItem('myFavorites', JSON.stringify(favorites));
        }
    }

    // 从常用中移除
    function removeFromFavorites(url) {
        let favorites = JSON.parse(localStorage.getItem('myFavorites') || '[]');
        favorites = favorites.filter(item => item.url !== url);
        localStorage.setItem('myFavorites', JSON.stringify(favorites));
    }

    async function applyFavorites($card, cardData) {
        // 获取生效区域
        const $favoritesSection = $(`#content .content-section:has(h4:contains(${categoryName}))`);
        const $favoritesRow = $favoritesSection.next('.row');
        const $emptyMessage = $favoritesRow.find('.col-12.text-muted');

        // 如果当前显示"暂无内容"，则移除该提示
        if ($emptyMessage.length) {
            $emptyMessage.remove();
        }

        // 检查是否已存在该卡片
        const existingCard = $favoritesRow.find(`.url-card a[data-url="${cardData.url}"]`);
        if (existingCard.length) {
            return; // 如果已存在则不重复添加
        }

        // 获取卡片HTML并移除右键菜单部分
        const $tmpCard = $card.clone();

        // 移除"添加到XXX"按钮
        $tmpCard.find('.add-to-favorites').remove();

        // 确保"从XXX中移除"按钮显示
        $tmpCard.find('.remove-from-favorites').show();

        // 创建新卡片（不包含'添加到XXX'按钮）
        const $newCard = $(`
            <div class="url-card col-6 col-sm-6 col-md-4 col-xl-5a col-xxl-6a position-relative">
                ${$tmpCard.html()}
            </div>
        `);

        // 添加到生效区域
        $favoritesRow.append($newCard);

        // 初始化右键菜单
        initContextMenu($newCard);

        // 强制重排保证DOM更新
        await new Promise(resolve => requestAnimationFrame(resolve));
    }

    async function removeFromFavoritesSection(url) {
        // 获取生效区域
        const $favoritesSection = $(`#content .content-section:has(h4:contains(${categoryName}))`);
        const $favoritesRow = $favoritesSection.next('.row');

        // 移除对应卡片
        const $card = $favoritesRow.find(`.url-card a[data-url="${url}"]`).closest('.url-card').remove();

        if ($card.length) {
            $card.remove();

            // 等待DOM更新
            await new Promise(resolve => requestAnimationFrame(resolve));

            // 如果没有卡片了，显示"暂无内容"提示
            if ($favoritesRow.find('.url-card').length === 0) {
                $favoritesRow.html(`
                    <div class="col-12 text-muted py-4">
                        <i class="iconfont icon-inbox mr-2"></i>暂无相关内容
                    </div>
                `);
            }
        }
    }

    // 加载并渲染收藏的卡片
    function loadFavorites() {
        return new Promise((resolve) => {
            try {
                const favorites = JSON.parse(localStorage.getItem('myFavorites') || '[]');
                const $favoritesSection = $(`#content .content-section:has(h4:contains(${categoryName}))`);
                const $favoritesRow = $favoritesSection.next('.row');

                // 为所有相关卡片添加关联图标
                $('#content .row .url-card').each(function() {
                    const $card = $(this);
                    const url = $card.find('a[data-url]').data('url');
                    if (checkIfFavorite(url)) {
                        addHeartIcon($card);
                    }
                });

                // 清空生效区域中现有内容
                $favoritesRow.empty();

                if (favorites.length === 0) {
                    $favoritesRow.html(`
                    <div class="col-12 text-muted py-4">
                        <i class="iconfont icon-inbox mr-2"></i>暂无相关内容
                    </div>
                `);
                    return resolve(true);
                }

                // 使用文档片段提高性能
                const fragment = document.createDocumentFragment();

                // 渲染每个卡片
                for (const item of favorites) {
                    const $card = createFavoriteCard(item);
                    fragment.appendChild($card[0]);
                }

                // 单次DOM操作（同步）
                $favoritesRow.append(fragment);

                resolve(true);
            } catch (error) {
                console.error(`加载${categoryName}失败:`, error);
                resolve(false);
            }
        })
    }

    // 添加关联图标
    function addHeartIcon($card) {
        // 先移除可能已存在的图标，再插入新图标
        $card.find('.url-body > a.card .text-sm strong')
            .next('.iconfont.icon-heart').remove()  // 先清理现有图标
            .end()  // 返回到strong选择器
            .after('<i class="iconfont icon-heart ml-2" style="color: #dc3545"></i>');
    }

    // 移除关联图标
    function removeHeartIcon($card) {
        $card.find('.url-body > a.card .text-sm strong')
            .next('.iconfont.icon-heart').remove();
    }

    // 创建收藏卡片 DOM
    function createFavoriteCard(item) {
        return $(`
            <div class="url-card col-6 col-sm-6 col-md-4 col-xl-5a col-xxl-6a position-relative">
                <div class="url-body default">
                    <a href="${item.url}" target="_blank" rel="noopener noreferrer" 
                        data-id="" data-url="${item.url}" 
                        class="card no-c mb-4" 
                        data-toggle="tooltip" 
                        data-placement="bottom" 
                        data-name="${item.title}" 
                        data-description="${item.description}">
                        <div class="card-body" style="background-color: rgb(44, 46, 47);">
                            <div class="url-content d-flex align-items-center">
                                <div class="url-img mr-2 d-flex align-items-center justify-content-center">
                                    <img src="${item.logo}" data-src="${item.logo}" width="auto" height="32" 
                                        alt="${item.title}的Logo"
                                        class="lazyload" loading="lazy" 
                                        style="max-height: 100%; width: auto;"
                                        sizes="(max-width: 100px) 100vw, 50vw"
                                        onerror="this.src='images/nav/default/default.png?v=v1'">
                                </div>
                                <div class="url-info flex-fill">
                                    <div class="text-sm overflowClip_1 d-flex align-items-center">
                                        <strong style="color: rgb(255, 255, 255);">${item.title}</strong>
                                    </div>
                                    <p class="overflowClip_1 m-0 text-xs" style="color: #6c757d;" 
                                        data-bs-toggle="tooltip" title="${item.description}">
                                        ${item.description}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </a>
                    <a href="${item.url}" class="togo text-center text-muted is-views" 
                        data-id="689" data-toggle="tooltip" 
                        data-placement="right" title="直达 ${item.title}" 
                        aria-label="直达 ${item.title}" rel="nofollow">
                        <i class="iconfont icon-goto" aria-hidden="true"></i>
                    </a>
                </div>
                <div class="btn-group context-menu dropdown-menu shadow position-absolute" role="group" aria-labelledby="contextMenuTrigger">
                    <button type="button" class="btn btn-info dropdown-item remove-from-favorites">
                        <i class="iconfont icon-delete mr-2"></i>从${categoryName}中移除
                    </button>
                </div>
            </div>
        `);
    }


    // 初始化所有卡片的右键菜单
    function initContextMenu($card) {
        $card.on('contextmenu', function (e) {
            e.preventDefault();
            const $this = $(this);
            const url = $this.find('a[data-url]').data('url');

            // 隐藏所有其他菜单
            $('.context-menu').removeClass('show');

            // 检查是否在常用中
            const isFavorite = checkIfFavorite(url);

            $this.find('.add-to-favorites').toggle(!isFavorite);
            $this.find('.remove-from-favorites').toggle(isFavorite);

            // 定位并显示菜单
            const menu = $this.find('.context-menu');
            menu.css({
                'top': `${e.pageY}px`,
                'left': `${e.pageX}px`
            }).addClass('show');
        });
    }

    function init() {
        try {
            // 1. 初始化
            loadFavorites().then(success => {
                if (success) {
                    console.debug('[module] [favorites] 初始化完成');
                } else {
                    console.warn('[module] [favorites] 初始化完成但有错误');
                }
            });

            // 2. 更新卡片的右键菜单
            $('#content .row .url-card').each(function () {
                initContextMenu($(this));
            });
        } catch (error) {
            console.error('[module] [favorites] 初始化失败:', error);
        }
    }

    init();
})(window.jQuery);